<template>
  <div style="width: 100%">
    <div class="thead">
      <el-input
        v-model="searchModel.condition"
        placeholder="请输入搜索内容"
        style="margin-right: 30px; width: 300px"
      />
      <el-button type="primary" :icon="Search" @click="load()">搜索</el-button>
      <el-button
        type="primary"
        @click="add()"
        style="margin-left: auto;x"
        >新增</el-button
      >
      <el-button type="danger" @click="deleteSelected()">批量删除</el-button>
    </div>
    
    <el-table
      style="width: 100%"
      stripe
      border
      highlight-current-row
      :data="userList"
      @selection-change="handleSelectionChangeDepartment"
    >
 

      
      
        <el-table-column type="selection" label="全选" width="55" style="margin:auto">   
        </el-table-column>
        <template slot-scope="scope">
          <span style="cursor: pointer" @click="deleteDepartmentRow(scope.$index, scope.row)">
            <i class="el-icon-delete"></i>
          </span>
        </template>
     

      <el-table-column
        align="center"
        label="用户名"
        prop="username"
        width="180"
      ></el-table-column>
      <el-table-column
        align="center"
        label="用户昵称"
        prop="userNick"
        width="180"
      ></el-table-column>
      <el-table-column
        align="center"
        label="邮箱"
        prop="email"
        width="180"
      ></el-table-column>
      <el-table-column
        align="center"
        label="电话"
        prop="phone"
        width="180"
      ></el-table-column>
      <el-table-column
        align="center"
        label="地址"
        prop="address"
      ></el-table-column>
      <el-table-column align="center" label="操作">
        <template #default="scope">
          <!-- @click="handleEdit(scope.row)"  -->
          <el-button size="mini" type="primary" @click="handleEdit(scope.row)"
            >编辑</el-button
          >
          <!--scope.row当前行的对象-->
          <el-popconfirm
            title="Are you sure to delete this?"
            @confirm="handleDelete(scope.row)"
          >
            <template #reference>
              <el-button size="mini" type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination
        hide-on-single-page
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="searchModel.pageNow"
        :page-sizes="[5, 10, 30, 50]"
        :page-size="searchModel.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount"
      >
      </el-pagination>
    </div>

    <!-- 编辑用户信息 -->
    <el-dialog
      class="dialog"
      v-model="editDialogVisible"
      :title="formTitle"
      width="40%"
      
      :before-close="closeForm"
    >
    
    <div class="tableItem" style="margin-top: 15px;">
        <span>用户名 :  </span>
        <div class="innerInput" style="margin-left: 14px;">
          <el-input v-model="editUser.username" placeholder="用户名" />
        </div>
      </div>

     <div class="tableItem"  v-if="formTitle === '新增用户'">
        <span>用户密码 :</span>
        <div class="innerInput">
          <el-input v-model="editUser.password" placeholder="密码"/>
        </div>
      </div>

      <div class="tableItem">
        <span>用户昵称 :</span>
        <div class="innerInput">
          <el-input v-model="editUser.userNick" placeholder="用户昵称"/>
        </div>
      </div>


      <div class="tableItem">
        <span>用户邮箱 :</span>
        <div class="innerInput">
          <el-input v-model="editUser.email" placeholder="邮箱" />
        </div>
      </div>


      <div class="tableItem">
        <span>用户电话 :</span>
        <div class="innerInput">
          <el-input v-model="editUser.phone" placeholder="电话" />
        </div>
      </div>


      <div class="tableItem" style="margin-bottom: 25px;">
        <span>用户地址 :</span>
        <div class="innerInput">
          <el-input v-model="editUser.address" placeholder="地址"/>
        </div>
      </div>



      <div class="roleList">
        <el-checkbox-group v-model="userRoleList">
         
            <el-checkbox-button
            v-for="role in allRole"
            :key="role.id"
            :label="role.id"
            >{{ role.roleDesc }}
          </el-checkbox-button>
          
        </el-checkbox-group>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeForm">取消</el-button>
          <el-button type="primary" @click="updateUser"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import userApi from "../../api/user";
import roleApi from "@/api/role";
import { ElMessage } from "element-plus";
import ElementPlus from "element-plus";
import "element-plus/dist/index.css";
import { Search } from "@element-plus/icons-vue";
import store from "@/store";
export default {
  data() {
    return {
      userList: [],
      totalCount: 0, // 总数默认为0
      searchModel: {
        pageNow: 1,
        pageSize: 10,
        condition: "",
        formTitle: "",
      },
      editDialogVisible: false,
      editUser: [],
      userRoleList: [],
      allRole: [],
      multipleSelectionDepartment: [],
    };
  },
  created() {
    this.load();
    this.getAllRole();  
  },
  methods: {
    load() {
      userApi.getUserList(this.searchModel).then((res) => {
        this.userList = res.data.records;
        this.totalCount = res.data.total;
      });
    },
    getAllRole() {
      roleApi.getAllrole().then((res) => {
        this.allRole = res.data;
      });
    },
    handleSizeChange(pageSize) {
      this.searchModel.pageSize = pageSize;
      this.load();
    },
    handleCurrentChange(pageNow) {
      this.searchModel.pageNow = pageNow;
      this.load();
    },
    handleEdit(editUser) {
      this.formTitle = "用户信息";
      (this.editDialogVisible = true), (this.editUser = editUser);
      userApi.getUserRole(editUser.username).then((res) => {
        if (res.data.length) {
          res.data.forEach((element) => {
            if(element!=null){
              this.userRoleList.push(element.id);
            }
           
          });
        }
      });
    },
    handleDelete(user) {
      userApi.deleteUser(user).then((res) => {
        this.load();
      });
    },
    clearForm() {
      this.editUser = [];
      this.userRoleList = [];
    },
    closeForm() {
      this.clearForm();
      this.editDialogVisible = false;
    },
    updateUser() {
      if (this.formTitle === "新增用户") {
        userApi.saveUser(this.editUser, this.userRoleList).then((res) => {
          ElMessage({
            showClose: true,
            message: "添加用户成功！",
            type: "success",
          });
        });
        this.closeForm();
      } else {
        //更新 用户
        userApi.updateUser(this.editUser);
        //更新用户角色
        userApi
          .updateUserRole(this.editUser.id, this.userRoleList)
          .then((res) => {
            ElMessage({
              showClose: true,
              message: "更新用户数据成功",
              type: "success",
            });
          });
        this.closeForm();
      }
    },
    add() {
      this.editUser = [];
      this.userRoleList = [];
      this.editDialogVisible = true;
      this.formTitle = "新增用户";
    },
    //批量删除
    handleSelectionChangeDepartment(val) {
      this.multipleSelectionDepartment = val;
    },
    deleteSelected(){
      this.$confirm('此操作将批量删除用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let val = []
        this.multipleSelectionDepartment.forEach(deluser=>{
            if(deluser!= null && deluser!=undefined){
                val.push(deluser.id)
            }
        })     //选中的值
        userApi.removeBatch(val).then(res=>{
          ElMessage({
            showClose: true,
            message: "删除成功！",
            type: "success",
          });
          this.load()
        }).catch(err=>{
          ElMessage({
            showClose: true,
            message: "删除失败！  原因: "+ err ,
            type: "success",
          });
        }
      )
        console.log(val)
      })
    },
  },
};
</script>
<style>
.block {
  margin-top: 20px;
  margin-left: 50px;
}
.thead {
  display: flex;
  margin-bottom: 10px;
}
.tableItem{
  display: flex;
  margin-top: 5px;
  text-align: center;
  margin-bottom: 8px;
  justify-content: center;
  
}
.tableItem span{
  margin-top: 5px;
  margin-right: 10px;
}
.innerInput{
  width: 300px;
}
.roleList{
  margin-left: 100px;
  margin-right: 70px;
}

</style>
